package cn.juque.lucenecandy.core.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.extra.spring.SpringUtil;
import cn.juque.common.constants.NumberConstant;
import cn.juque.common.utils.HttpClientUtil;
import cn.juque.lucenecandy.core.config.LuceneCandyConfig;
import cn.juque.lucenecandy.core.constants.StrConstant;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>SignatureUtil</li>
 * </ul>
 * @date 2023-12-27
 **/
public class SignatureUtil {

    private SignatureUtil() {
    }

    public static String buildUrl(String url) {
        return HttpClientUtil.joinParam(url, buildQuery());
    }

    public static Map<String, Object> buildQuery() {
        String randomStr = RandomUtil.randomString(NumberConstant.SIX);
        Long timestamp = System.currentTimeMillis();
        String signature = createSignature(timestamp, randomStr);
        Map<String, Object> map = new HashMap<>(3);
        map.put(StrConstant.SIGNATURE, signature);
        map.put(StrConstant.TIMESTAMP, timestamp);
        map.put(StrConstant.RANDOM_STR, randomStr);
        return map;
    }

    public static String createSignature(Long timestamp, String randomStr) {
        String str = randomStr + timestamp;
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, str.getBytes(StandardCharsets.UTF_8));
        LuceneCandyConfig luceneCandyConfig = SpringUtil.getBean(LuceneCandyConfig.BEAN_ID);
        return mac.digestHex(luceneCandyConfig.getSecret());
    }

    public static Boolean checkSignature(Long timestamp, String randomStr, String signature) {
        int limit = NumberConstant.FIVE * NumberConstant.ONE_THOUSAND;
        if (System.currentTimeMillis() - timestamp > limit) {
            return false;
        }
        String str = randomStr + timestamp;
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, str.getBytes(StandardCharsets.UTF_8));
        LuceneCandyConfig luceneCandyConfig = SpringUtil.getBean(LuceneCandyConfig.BEAN_ID);
        String rawToken = mac.digestHex(luceneCandyConfig.getSecret());
        return mac.verify(signature.getBytes(StandardCharsets.UTF_8), rawToken.getBytes(StandardCharsets.UTF_8));
    }
}
